package com.example.demo.controller;
import com.example.demo.entity.*;
import com.example.demo.service.UserService;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@RestController
public class UserController {
    private static String resource = new ApplicationHome().getDir().getAbsolutePath()+"\\src\\main\\resources\\";
//    private static String iconSrc = resource+"icons";
    private static String iconSrc = resource+"icons\\";
    private static String goodsSrc = resource+"goods\\";
    private static String sharesSrc = resource+"shares"+"\\";

    @Autowired
    private UserService userService;
//    @RequestMapping("/user/abc")
//    public User_Test2 getName(){
//        return new User_Test2("张三","01","1232342","124342","afsgfsdgsfdg");
//    }
    @RequestMapping(value = "/user/abcd")
    public synchronized List<User_Test2> getUser(){
        return userService.findAll();
    }

    //这里开始提交用户名密码的请求都使用post请求
    @RequestMapping(value = "/user/exist")
    public boolean exist(@RequestParam("admin") String admin){
        return userService.exist(admin);
    }
    @RequestMapping("/user/login")
    //登录接口
    public boolean login(@RequestParam("admin") String admin,@RequestParam("pswd") String pswd){
        System.out.println("admin:"+admin+",pswd:"+pswd);
        return userService.login(admin,pswd);
    }
    @RequestMapping("/user/modifypswd")
    public String modify_password(@RequestParam("account") String account,@RequestParam("password") String password){
        return userService.modify_password(account,password);
    }
    @RequestMapping("/user/getId")
    public String getId(String account){
        return userService.getId(account);
    }
    //输入昵称和账户密码生产新的账号
    @RequestMapping("/user/register")
    public boolean register(@RequestParam("nickName") String nickName,@RequestParam("account") String account,@RequestParam("password") String password,@RequestParam("customer") int customer,@RequestParam("business") int business){
        return userService.register(nickName,account,password,customer,business);
    }
    //产生随机昵称的注册接口
    @RequestMapping("/user/registerNoNickName")
    public boolean register(@RequestParam("account") String account,@RequestParam("password")String password,@RequestParam("customer")int customer,@RequestParam("business")int business){
        return userService.registerNoNickName(account,password,customer,business);
    }
    @RequestMapping("/user/getNickName")
    public String getNickNameByAccount(@RequestParam("account")String account){
        return userService.getNickNameByAccount(account);
    }
    //通过账号判断是否为已注册的用户
    @RequestMapping("/user/business/isCustomer")
    public boolean isCustomer(@RequestParam("account")String account){
        return userService.isCustomer(account);
    }
    //商家创建用户账号
    @RequestMapping("/user/business/businessCreateCustomer")
    public boolean businessCreateCustomer(@RequestParam("account")String account){
        return userService.businessCreateCustomer(account);
    }
    @RequestMapping("/user/customer/isBusiness")
    public boolean isBusiness(@RequestParam("account")String account){
        return userService.isBusiness(account);
    }
    // /admin下的接口:管理员接口
    // /user下的接口:用户通用接口
    // /user/customer下的接口:客户接口
    // /user/business下的接口:商家接口
    // /public下的接口:公共信息

    //头像上传测试接口
    @RequestMapping("/iconUpload")
    public boolean iconFileUpload(@RequestParam("file")MultipartFile file,@RequestParam("account")String id){
        if(file.isEmpty()){
            System.out.println("文件为空");
            return false;
        }
        ApplicationHome home = new ApplicationHome();
        String absPath = home.getDir().getAbsolutePath();
        String filePath = absPath+"\\src\\main\\resources\\icons\\"+id+".png";
        System.out.println(filePath);
        File iconFile = new File(filePath);

        try{
            if(!iconFile.exists()){
                iconFile.createNewFile();
            }
            file.transferTo(new File(filePath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }
    //通过id获取头像，如果找不到说明用户没有上传头像，发送默认头像
    @RequestMapping("/getIcon")
    public ResponseEntity<Resource> getIconById(@RequestParam("account") String id){
        File file = new File(iconSrc+id+".png");
        System.out.println(file.getName());
        if (!file.exists()){

            file = new File(iconSrc+"default.png");
            //如果这张图片不存在，发送默认头像
        }
        return showImg(file);
    }
    //拟定一个实现方案:前端发送一个商品id号到后端，后端查询数据库中id号对应的图片路径，将图片路径数组对象返回给前端，同时后端写一个接口，获取前端的路径，可以直接访问到
    //这些图片
    @RequestMapping("/picUpload")
    public boolean picUpload(@RequestParam("id")String id){
        //如果商家第一次创建店铺，则通过商品id来创建一个目录，在shops下，每次上传图片时
        //用户端需要查看商品详情页面时，可以直接通过商品id获取这个目录下的文件流
        File dir = new File(goodsSrc+'\\'+id);
        boolean res = dir.mkdir();
        System.out.println("创建文件结果:"+res);

        //resource下有一个shop目录，当有新的商品上架的时候，以当前商品的id号为目录名创建一个新的目录。这个目录下是这个商品的
        //商品详情图片
        return false;
    }
    //通过图片文件名获取分享图片
    @RequestMapping("/getSharePic")
    public ResponseEntity<Resource> getSharePic(@RequestParam("fileName")String fileName,@RequestParam("shareId")String shareId){
        String filePath = sharesSrc+shareId+"\\"+fileName;
        System.out.println(filePath);
        return this.userService.getImgFromSrc(filePath,false);
    }
    //通过图片文件名获取商品图片
    @RequestMapping("/getGoodsPic")
    public ResponseEntity<Resource> getGoodsPic(@RequestParam("fileName")String fileName,@RequestParam("goodsId")String goodsId){
        String filePath = goodsSrc+goodsId+"\\"+fileName;
        System.out.println(filePath);
        return this.userService.getImgFromSrc(filePath,true);
    }
    @RequestMapping("/getFirstGoodsPic")
    public ResponseEntity<Resource> getFirstGoodsPic(@RequestParam("goodsId")String goodsId){
        String filePath = goodsSrc+goodsId+"\\"+"0.png";
        return this.userService.getImgFromSrc(filePath,true);
    }
    @RequestMapping("/getFileList")
    public String[] getFileList(@RequestParam("goodsId")String goodsId){
//        shopsSrc+goodsId
        File directory = new File(goodsSrc+goodsId);
        File[] files = directory.listFiles();
        if(files == null){
            return new String[]{""};
        }else {
            String[] fileNames = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                fileNames[i] = files[i].getName();
            }
            return fileNames;
        }
    }
    @RequestMapping("/getShareImgFileNames")
    public String[] getFileName(@RequestParam("shareId")String shareId){
        File directory = new File(sharesSrc+shareId);
        if(directory.exists()){
            File[] files = directory.listFiles();
            String[] fileNames = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                fileNames[i] = files[i].getName();
            }
            return fileNames;
        }else {
            return new String[]{""};
        }

    }
    @RequestMapping("/getGoodsImgFileNames")
    public String[] getGoodsNames(@RequestParam("goodsId")String goodsId){
        File directory = new File(goodsSrc+goodsId);
        File[] files = directory.listFiles();
        if(files == null){
            System.out.println("没有文件");
            return new String[]{""};
        }
        String[] fileNames = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            fileNames[i] = files[i].getName();
        }
        return fileNames;
    }
    @RequestMapping("/addGoods")
    public boolean addNewGoods(@RequestBody GoodsDetail goodsDetail){
        System.out.println(goodsDetail.toString());
//        return true;
        return userService.addNewGoods(goodsDetail);
    }
    @RequestMapping("/getGoodsById")
    public GoodsDetail getGoodsById(@RequestParam("goodsId")String goodsId){return this.userService.getDetailById(goodsId);}
    //用户提交订单
//    @RequestMapping("/user/submit")
//    public boolean submitOrder(@RequestBody List<Order> orders){
//        return this.userService.userSubmitOrder(orders);
//    }
    @RequestMapping("/user/addNewAddress")
    public boolean addNewAddress(@RequestBody Address address){
        return this.userService.addNewAddress(address);
    }
    //showImg方法，通过inline的方式传递文件，参数为需要传递的file对象
    @RequestMapping("/getAllGoodsDetail")
    public GoodsDetail[] getAllGoodsDetails(){return this.userService.getAllGoodsDetails();}
    @RequestMapping("/getGoodsDetailLike")
    public GoodsDetail[] getGoodsDetailLike(@RequestParam("like")String like){return this.userService.getGoodsDetailLikeStr(like);}
    @RequestMapping("/addLabel")
    public int addLabel(@RequestBody Label label){return this.userService.addLabel(label);}
    @RequestMapping("/getUserId")
    public String getUserId(@RequestParam("admin")String admin,@RequestParam("password")String password){return this.userService.getUserId(admin,password);}
    @RequestMapping("/getLabelsById")
    public Label[] getLabelsByGoodsId(int goodsId){return this.userService.getLabelsByGoodsId(goodsId);}
    @RequestMapping("/uploadSharePics")
    public boolean uploadSharePics(@RequestParam("shares") MultipartFile[] files,@RequestParam("shareId")String shareId){
        System.out.println(shareId);
        return this.userService.uploadSharePics(files,shareId);
    }
    @RequestMapping("/uploadGoodsPics")
    public boolean uploadGoodsPics(@RequestParam("goods")MultipartFile[] files,@RequestParam("goodsId")String goodsId){
        System.out.println("goodsId:"+goodsId);
        return this.userService.uploadGoodsPics(files,goodsId);
    }
    @RequestMapping("/getGoodsId")
    public int getGoodsId(@RequestParam("timestamp")long timestamp,@RequestParam("businessId")String account){return this.userService.getGoodsId(timestamp,account);}
    @RequestMapping("/getShareId")
    public int getShareId(@RequestParam("timestamp")long timestamp,@RequestParam("account")String account){return userService.getShareId(timestamp,account);}
    @RequestMapping("/addNewShare")
    public boolean addNewShare(@RequestBody Share share){
        System.out.println(share.toString());
        return this.userService.addNewShare(share);
    }
    @RequestMapping("/getAllShare")
    public Share[] getAllShare(){return this.userService.getAllShare();}
    @RequestMapping("/getAccountByGoodsId")
    public String getAccountByGoodsId(@RequestParam("goodsId")String goodsId){return this.userService.getAccountByGoodsId(goodsId);}
    @RequestMapping("/getDetailsByBusinessId")
    public GoodsDetail[] getGoodsDetails(@RequestParam("businessId")String businessId){return this.userService.getDetailsByBusinessId(businessId);}

    //查询用户的店铺名称，如果不存在，则需要创建
    @RequestMapping("/getShopNameByBusinessId")
    public String getShopNameByBusinessId(@RequestParam("businessId")String businessId){return this.userService.getShopNameByBusinessId(businessId);}

    @RequestMapping("/getOrdersByAccount")
    public Order[] getOrdersByAccount(@RequestParam("account")String account){return this.userService.getOrdersByAccount(account);}

    @RequestMapping("/getOrdersByBusinessId")
    public Order[] getOrdersByBusinessId(@RequestParam("businessId")String businessId){return this.userService.getOrdersByBusinessId(businessId);}
    @RequestMapping("/setShopNameByAccount")
    public int setShopNameByAccount(@RequestParam("shopName")String shopName,@RequestParam("account")String account){return this.userService.setShopNameByAccount(shopName,account);}
    @RequestMapping("/updateGoodsDetail")
    public boolean updateGoodsDetail(@RequestBody GoodsDetail detail){return this.userService.updateGoodsDetail(detail);}
    @RequestMapping("/getDetailByClassAndGroup")
    public GoodsDetail[] getDetailsByClassAndGroup(int goodsClass,int goodsGroup){
        System.out.println("class:"+goodsClass+"group:"+goodsGroup);
        return this.userService.getDetailsByClassAngGroup(goodsClass,goodsGroup);
    }
    @RequestMapping("/user/submitOrder")
    public boolean submitOrder(@RequestBody Order[] orders){return this.userService.submitOrder(orders);}
    @RequestMapping("/updateOrderState")
    public boolean updateOrderState(@RequestBody Order order){return this.userService.updateOrderState(order);}
    @RequestMapping("/getAddressByAccount")
    public Address[] getAddressByAccount(@RequestParam("account")String account){return this.userService.getAddressByAccount(account);}
    @RequestMapping("/modifyMain")
    public boolean modifyMain(@RequestParam("id")int id,@RequestParam("account")String account){return this.userService.modifyMain(id,account);}
    @RequestMapping("/addAddress")
    public boolean addAddress(@RequestBody Address address){return this.userService.addAddress(address);}
    @RequestMapping("/getGoodsNameByGoodsId")
    public String getGoodsNameByGoodsId(@RequestParam("goodsId")String goodsId){return this.userService.getGoodsNameByGoodsId(goodsId);}
    private static ResponseEntity<Resource> showImg(File file){
        Resource resource = new FileSystemResource(file);
        String contentType;
        try {
            contentType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION,"inline;filename=\""+resource.getFilename()+"\"");
        headers.add("Content-Type",contentType);
        if(resource.exists()){
            return ResponseEntity.ok()
                    .headers(headers)
//                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(resource);
        }else {
            return ResponseEntity.notFound().build();

        }
    }

}
